package manager;

import java.awt.Dimension;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import softwareControl.TesteComandos;

/**
 *
 * @author Heitor
 */
public class Processor extends javax.swing.JFrame {
    
    private TesteComandos testCommands;

    private JFileChooser fileChooserIn = new JFileChooser();
    private JFileChooser fileChooserOut = new JFileChooser();
    
    private File[] files;
    
    private String directoryOut;
    private String pathJavaccBat;
    
    public Processor() {
        
        setLookAndFeel();
        initComponents();
        
        setPreferredSize(new Dimension(460,270));
        
        //setResizable(false);
        
        //jTextPane1.setEditable(false);
        //jTextPane2.setEditable(false);
        
        files = new File[0];
        directoryOut = "";
        
        pathJavaccBat = System.getProperty("user.dir") + "\\lib\\javacc-5_bin\\javacc.bat";
        
        fileChooserIn.setFileFilter(new javax.swing.filechooser.FileFilter(){
            @Override
            public boolean accept(File f){
                return f.getName().toLowerCase().endsWith(".jj") || f.isDirectory();
            }
            @Override
            public String getDescription() {
                return "Arquivos Javacc (.jj)";
            }
        });
        fileChooserOut.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        File pathInicial = new File(System.getProperty("user.dir") + "/src/");
        fileChooserIn.setCurrentDirectory(pathInicial);
        
        setTitle("Generator and Tester");
        setLocationRelativeTo(null);
        
    }
    
    private static void setLookAndFeel() {
//        try {
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//        }
//        catch(Exception e) {
//        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jlSelectJJ = new javax.swing.JLabel();
        jlDirectoryOut = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane2 = new javax.swing.JTextPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jbUpdate = new javax.swing.JButton();
        jbTest = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Processamento e Testes");

        jlSelectJJ.setText("Arquivos JJ");

        jlDirectoryOut.setText("Diretório de Saída");

        jScrollPane1.setViewportView(jTextPane2);

        jScrollPane2.setViewportView(jTextPane1);

        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jbUpdate.setText("Compilar");
        jbUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbUpdateActionPerformed(evt);
            }
        });

        jbTest.setText("Testar");
        jbTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbTestActionPerformed(evt);
            }
        });

        jCheckBox1.setText("Diretório de Saída igual diretório do primeiro arquivo JJ");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbTest)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbUpdate)
                        .addGap(18, 18, 18)
                        .addComponent(jCheckBox1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlDirectoryOut)
                            .addComponent(jlSelectJJ))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                            .addComponent(jScrollPane1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(146, 146, 146)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlSelectJJ)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlDirectoryOut)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbUpdate)
                    .addComponent(jbTest)
                    .addComponent(jCheckBox1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        // TODO add your handling code here:
        
        if (jCheckBox1.isSelected()){
            
            String[] aux1 = jTextPane1.getText().split(";");
            String[] aux2 = aux1[0].split("\\\\");
            String pathAux = "";
            for(int i=0; i<aux2.length-1; i++){
                if(pathAux.equals("")){
                    pathAux = aux2[i];
                } else{
                    pathAux = pathAux + "/" + aux2[i];
                }
            }
            jTextPane2.setText(pathAux);
            jButton2.setVisible(false);
        } else{
            
            jTextPane2.setText("");
            jButton2.setVisible(true);
        }
        
        directoryOut = jTextPane2.getText();
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        // Possibilita a seleção de vários arquivos
        fileChooserIn.setMultiSelectionEnabled(true);
        fileChooserIn.setDialogTitle("Arquivos JavaCC(.jj)");
        fileChooserIn.showOpenDialog(this);

        // Retorna os arquivos selecionados. Este método retorna vazio se
        // o modo de múltipla seleção de arquivos não estiver ativada.
        files = fileChooserIn.getSelectedFiles();
        
        for(int i=0; i<files.length; i++){
            if(!jTextPane1.getText().equals("")){
                jTextPane1.setText(jTextPane1.getText() + "; " + files[i].toString());
            } else{
                jTextPane1.setText(files[i].toString());
            }
        }
        
        if (jCheckBox1.isSelected()){
            
            String[] aux1 = jTextPane1.getText().split(";");
            String[] aux2 = aux1[0].split("\\\\");
            String pathAux = "";
            for(int i=0; i<aux2.length-1; i++){
                if(pathAux.equals("")){
                    pathAux = aux2[i];
                } else{
                    pathAux = pathAux + "/" + aux2[i];
                }
            }
            jTextPane2.setText(pathAux);
            jButton2.setVisible(false);
        } else{
            
            jTextPane2.setText("");
            jButton2.setVisible(true);
        }
        
        directoryOut = jTextPane2.getText();

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        fileChooserOut.setDialogTitle("Diretório das classes geradas");

        directoryOut = "";
        
        if(fileChooserOut.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){

            //Processando o diretorio escolhido
            directoryOut = fileChooserOut.getSelectedFile().getAbsolutePath();
        }
        
        jTextPane2.setText(directoryOut);
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jbUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbUpdateActionPerformed
        // TODO add your handling code here:
        if(files.length > 0){
            if(!directoryOut.equals("")){
                try {
                    for(int i=0; i<files.length; i++){
                        Runtime.getRuntime().exec("cmd /c start " + pathJavaccBat + " " + files[i], null, new File(directoryOut));
                    }
                } catch (Exception ex) {
                    System.out.println("[Erro] " + ex.toString());
                }
            } else{
                JOptionPane.showMessageDialog(null, "Não foi possível carregar o diretório destino", "Aviso", JOptionPane.ERROR_MESSAGE);
            }
        } else{
            if(!directoryOut.equals("")){
                JOptionPane.showMessageDialog(null, "Não foi possível carregar o(s) arquivo(s) JJ", "Aviso", JOptionPane.ERROR_MESSAGE);
            } else{
                JOptionPane.showMessageDialog(null, "Não foi possível carregar o diretório destino e o(s) arquivo(s) JJ", "Aviso", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jbUpdateActionPerformed

    private void jbTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbTestActionPerformed
        
        testCommands = new TesteComandos();
        
        testCommands.testeGetPaths();
        //testCommands.testeShowMote();
        //testCommands.testeShowStatus();
        //testCommands.testeGetNetwork();
        //testCommands.testeGetSystem();
        
        //testCommands.testeAlarmOpen();
    }//GEN-LAST:event_jbTestActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Processor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Processor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Processor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Processor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new Processor().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JTextPane jTextPane2;
    private javax.swing.JButton jbTest;
    private javax.swing.JButton jbUpdate;
    private javax.swing.JLabel jlDirectoryOut;
    private javax.swing.JLabel jlSelectJJ;
    // End of variables declaration//GEN-END:variables
}
